﻿package com.badibadi.activity;

import java.util.HashMap;
import java.util.Map;

import com.badibadi.fragment.ActivityReadingOffLineFragment;
import com.badibadi.fragment.LogReadingFragment0;
import com.badibadi.fragment.LogReadingFragment0.setActivityView;
import com.badibadi.fragment.LogReadingFragment1;
import com.badibadi.fragment.LogReadingFragment2;
import com.badibadi.infos.Results;
import com.badibadi.mytools.CommonUtils;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.TabHostUtils;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;
import com.badibadi.uniclubber.R.layout;
import com.badibadi.uniclubber.R.menu;
import com.libjph.util.JsonUtil;
import com.libjph.util.StringUtil;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;

/**
 * 只需要传rid就行了。 Intent record record
 * 
 * @author Administrator record 记录阅读
 */
public class LogReadingActivity extends BaseActivity {

	LinearLayout ll_bottom_btns;
	private String TAG = "LogReadingActivity";
	private TabHost mTabHost;
	private LogReadingFragment0 fragment;
	private LogReadingFragment1 fragment1;
	private LogReadingFragment2 fragment2;

	private String rid = "18", cid = null, admin_id = null,
			record_fq_uid = null;
	private String KEY0 = "TITLE";
	private String KEY1 = "VIEW";
	private String KEY2 = "DISCUSS";
	private String KEY3 = "COLLECT";
	private FragmentManager manager;
	// title的isRun
	private boolean isRun = true;
	// view浏览的isRun
	private boolean isRun1 = true;
	// discuss的isRun
	private boolean isRun2 = true;
	// collect的isRun
	private boolean isRun3 = true;
	TextView tv_title, tv_view, tv_discuss, tv_collect;
	com.badibadi.infos.RecordToInfos recordToInfos;
	RelativeLayout Rl_collect;
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:// 标题
				Utils.ExitPrgress(LogReadingActivity.this);
				tv_title.setText("" + msg.getData().getString(KEY0));
				isRun = false;
				break;
			case 2:// 浏览次数
				Utils.ExitPrgress(LogReadingActivity.this);
				tv_view.setText("" + msg.getData().getString(KEY1));
				isRun1 = false;
				break;

			case 3:// 评论
				Utils.ExitPrgress(LogReadingActivity.this);
				tv_discuss.setText("" + msg.getData().getString(KEY2));
				isRun2 = false;
				break;
			case 4:// 收藏
				Utils.ExitPrgress(LogReadingActivity.this);
				tv_collect.setText("" + msg.getData().getString(KEY3));
				isRun3 = false;
				break;
			case 5:// 网络错误
				Utils.ExitPrgress(LogReadingActivity.this);
				try {
					Utils.showMessage(LogReadingActivity.this, getResources()
							.getString(R.string.l_net_error));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 6:// 网络错误
				Utils.ExitPrgress(LogReadingActivity.this);
				try {
					Utils.showMessage(LogReadingActivity.this, getResources()
							.getString(R.string.SystemError));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 7:// 网络错误
				Utils.ExitPrgress(LogReadingActivity.this);
				try {
					Utils.showMessage(LogReadingActivity.this, getResources()
							.getString(R.string.l_xb79));
					tv_collect
							.setText(""
									+ (Integer.parseInt(tv_collect.getText()
											.toString()) + 1));
					// tv_collect.setText("" + msg.getData().getString(KEY3));
					// isRun3 = false;
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 8:// 网络错误
				Utils.ExitPrgress(LogReadingActivity.this);
				try {
					Utils.showMessage(LogReadingActivity.this, getResources()
							.getString(R.string.l_xb80));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 9:
				Utils.ExitPrgress(LogReadingActivity.this);
				try {
					init();
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 10:
				Utils.ExitPrgress(LogReadingActivity.this);
				try {
					// Utils.showMessage(LogReadingActivity.this,
					// "操作失败,你已经收藏了,不能重复收藏");
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		goToTheTitle();
		setContentView(R.layout.activity_log_reading);
		try {
			rid = getIntent().getStringExtra("rid");// 只需要传rid就行了

			// cid = getIntent().getStringExtra("cid");
			// admin_id = getIntent().getStringExtra("admin_id");
			// record_fq_uid =
			// getIntent().getStringExtra("jilu_fabiao_uid");//记录的发起者
		} catch (Exception e) {
			// TODO: handle exception
		}
		ll_bottom_btns = (LinearLayout) this.findViewById(R.id.ll_bottom_btns);
		Constants.is_shuaxin = false;
		// setBottomVisible(true);
		// if(rid==null)
		// {
		// rid="18";
		// }
		RecordToInfos();
	}

	public void setBottomVisible(boolean isOpen) {
		//
		if (isOpen == true) {
			ll_bottom_btns.setVisibility(View.VISIBLE);
		} else {
			ll_bottom_btns.setVisibility(View.GONE);
		}

	}

	/**
	 * 根据记录ID，查询出俱乐部ID，管理员ID，和纪录发起者ID-----POST
	 * 
	 * @param $rid
	 *            ; 记录ID 记录id，把对应的俱乐部id，管理员id和记录发起者id
	 */
	private void RecordToInfos() {
		Utils.showPrgress(LogReadingActivity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("rid", rid);
				String content = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "commonality/recordToInfos");
				if (content != null) {
					//
					Results results3 = Utils.checkResult_NNN(
							LogReadingActivity.this, content);
					if (results3 != null
							&& !results3.getRetmsg().equals("null")) {
						// private String rid = "18", cid = null, admin_id =
						// null,
						// record_fq_uid = null;
						// RecordToInfos
						try {
							recordToInfos = JsonUtil.getEntityByJsonString(
									results3.getRetmsg(),
									com.badibadi.infos.RecordToInfos.class);

							cid = recordToInfos.getClub_id();
							admin_id = recordToInfos.getClubAdminUid();
							record_fq_uid = recordToInfos.getUid();
						} catch (Exception e) {
							// TODO Auto-generated catch block

						}

						mHandler.sendEmptyMessage(9);
					} else {
						mHandler.sendEmptyMessage(6);
					}
				} else {
					mHandler.sendEmptyMessage(6);
				}
			}
		});
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		if (Constants.is_shuaxin) {
			Constants.is_shuaxin = false;
			LoadingFragment(0);
		}
	}

	private void init() {
		// 收藏按钮
		Rl_collect = (RelativeLayout) this.findViewById(R.id.Rl_collect);
		Rl_collect.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!Utils.getUid(LogReadingActivity.this).equals("")) {
					if (isRun3 == false) {
						if (cid == null) {
							cid = "0";
						}
						collect(cid, record_fq_uid, rid, "record");
					}
				} else {
					Utils.showMessage(LogReadingActivity.this, getResources()
							.getString(R.string.l_xb10));
				}
			}
		});
		manager = getSupportFragmentManager();
		tv_title = (TextView) this.findViewById(R.id.title);
		tv_view = (TextView) this.findViewById(R.id.view);
		tv_discuss = (TextView) this.findViewById(R.id.discuss);
		tv_collect = (TextView) this.findViewById(R.id.collect);

		this.findViewById(R.id.return_btn).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						finish();
					}
				});

		this.findViewById(R.id.record).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						if (!Utils.getUid(LogReadingActivity.this).equals("")) {
							if (cid != null && !cid.equals("0")) {
								if (admin_id.equals(Utils
										.getUid(LogReadingActivity.this))
										|| record_fq_uid.equals(Utils
												.getUid(LogReadingActivity.this))) {
									Intent intent = new Intent(
											LogReadingActivity.this,
											EditTheRecordActivity.class);
									intent.putExtra("rid", rid);
									intent.putExtra("cid", cid);
									//
									startActivity(intent);
								} else {
									Utils.showMessage(
											LogReadingActivity.this,
											getResources().getString(
													R.string.l_xb81));
								}
							} else {
								if (record_fq_uid.equals(Utils
										.getUid(LogReadingActivity.this))) {
									Intent intent = new Intent(
											LogReadingActivity.this,
											EditTheRecordActivity.class);
									intent.putExtra("rid", rid);
									// intent.putExtra("cid", cid);
									//
									startActivity(intent);
								} else {
									Utils.showMessage(
											LogReadingActivity.this,
											getResources().getString(
													R.string.l_xb82));
								}
							}
						} else {
							Utils.showMessage(LogReadingActivity.this,
									getResources().getString(R.string.l_xb10));
						}
					}
				});

		initTitleAndViewAndDiscussAndCollect();

		// fragment.setRecordTitle(new setActivityView() {
		//
		// @Override
		// public void setRecordData(final String title, int view, final int
		// discuss, int share) {
		// // TODO Auto-generated method stub
		//
		// // if(title!=null)
		// // {
		// // tv_title.setText(""+title);
		// // }
		// }
		// });
		settingTabHost();
		LoadingFragment(0);

	}

	/**
	 * 这里显示的是一个是标签，一个是
	 */
	private void initTitleAndViewAndDiscussAndCollect() {
		// TODO Auto-generated method stub
		// 1.更新Title的线程
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				while (isRun) {
					//
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block

					}

					fragment.setRecordTitle(new setActivityView() {
						//
						@Override
						public void setRecordData(final String title, int view,
								final int discuss, int share) {
							// TODO Auto-generated method stub
							if (!StringUtil.isNullOrEmpty(title)) {
								Message msg = new Message();
								msg.what = 1;
								Bundle bun = new Bundle();
								bun.putString(KEY0, "" + title);
								msg.setData(bun);
								mHandler.sendMessage(msg);
							}
						}
					});

				}

			}
		}).start();

		// 2.更新浏览的线程
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				while (isRun1) {
					//
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block

					}

					fragment.setRecordTitle(new setActivityView() {
						//
						@Override
						public void setRecordData(final String title, int view,
								final int discuss, int share) {
							// TODO Auto-generated method stub

							if (view != -1) {
								Message msg = new Message();
								msg.what = 2;
								Bundle bun = new Bundle();
								bun.putString(KEY1, "" + view);
								msg.setData(bun);
								mHandler.sendMessage(msg);
							}
						}
					});

				}

			}
		}).start();
		// 3.更新评论数量的线程
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				while (isRun2) {
					//
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block

					}

					fragment.setRecordTitle(new setActivityView() {
						//
						@Override
						public void setRecordData(final String title, int view,
								final int discuss, int share) {
							// TODO Auto-generated method stub

							if (discuss != -1) {
								Message msg = new Message();
								msg.what = 3;
								Bundle bun = new Bundle();
								bun.putString(KEY2, "" + discuss);
								msg.setData(bun);
								mHandler.sendMessage(msg);
							}
						}
					});

				}

			}
		}).start();

		// 4.更新收藏数量的线程
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				while (isRun3) {
					//
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block

					}

					fragment.setRecordTitle(new setActivityView() {
						//
						@Override
						public void setRecordData(final String title, int view,
								final int discuss, int collect) {
							// TODO Auto-generated method stub
							if (collect != -1) {
								Message msg = new Message();
								msg.what = 4;
								Bundle bun = new Bundle();
								bun.putString(KEY3, "" + collect);
								msg.setData(bun);
								mHandler.sendMessage(msg);
							}
						}
					});

				}

			}
		}).start();

	}

	private void LoadingFragment(int num) {
		// TODO Auto-generated method stub
		FragmentTransaction transaction = manager.beginTransaction();
		switch (num) {
		case 0:
			FragmentTransaction transaction2 = manager.beginTransaction();
			fragment = LogReadingFragment0.getInstance();
			Bundle bun = new Bundle();
			bun.putString("rid", rid);
			bun.putString("cid", cid);
			bun.putString("admin_id", admin_id);
			fragment.setArguments(bun);
			transaction2.replace(R.id.log_rading_layout, fragment,
					"logReadingFragment0");
			transaction2.commit();
			break;
		case 1:
			//
			FragmentTransaction transaction3 = manager.beginTransaction();
			fragment1 = LogReadingFragment1.getInstance();
			Bundle bun1 = new Bundle();
			bun1.putString("rid", rid);
			fragment1.setArguments(bun1);

			transaction3.replace(R.id.log_rading_layout, fragment1,
					"logReadingFragment1");
			transaction3.commit();
			break;
		case 2:

			FragmentTransaction transaction4 = manager.beginTransaction();
			fragment2 = LogReadingFragment2.getInstance();
			Bundle bun2 = new Bundle();
			bun2.putString("rid", rid);
			fragment2.setArguments(bun2);
			transaction4.replace(R.id.log_rading_layout, fragment2,
					"logReadingFragment2");
			transaction4.commit();
			break;
		}

	}

	private void settingTabHost() {
		// TODO Auto-generated method stub
		mTabHost = (TabHost) this.findViewById(R.id.log_reading_tabHost);
		mTabHost.setup();
		mTabHost.addTab(mTabHost
				.newTabSpec("logReading one")
				.setIndicator(getResources().getString(R.string.Content),
						getResources().getDrawable(R.drawable.ic_launcher))
				.setContent(R.id.tab1));
		mTabHost.addTab(mTabHost
				.newTabSpec("logReading two")
				.setIndicator(getResources().getString(R.string.picture),
						getResources().getDrawable(R.drawable.ic_launcher))
				.setContent(R.id.tab2));
		mTabHost.addTab(mTabHost
				.newTabSpec("logReading three")
				.setIndicator(getResources().getString(R.string.wx2_28),
						getResources().getDrawable(R.drawable.ic_launcher))
				.setContent(R.id.tab3));
		TabHostUtils.SetTabHost(this, mTabHost);
		mTabHost.setOnTabChangedListener(new OnTabChangeListener() {

			@Override
			public void onTabChanged(String tabId) {
				// TODO Auto-generated method stub

				switch (mTabHost.getCurrentTab()) {
				case 0:
					setBottomVisible(true);
					LoadingFragment(0);
					break;
				case 1:
					setBottomVisible(false);
					LoadingFragment(1);
					break;
				case 2:
					setBottomVisible(false);
					LoadingFragment(2);
					break;
				}
			}
		});

	}

	/**
	 * 用户+俱乐部 收藏的操作接口 提交方式GET
	 * 
	 * @param $uid
	 *            ;//收藏人的id
	 * @param $cid
	 *            ;//俱乐部收藏-------仅有record，humor_trends 这两种收藏方式，当为个人收藏时，值为0
	 * @param $nuid
	 *            ;//被收藏内容所属的用户id
	 * @param $nid
	 *            ;//被收藏的内容id
	 * @param $type
	 *            ;//被收藏的类型-----个人（3种）：photo_img，record，humor_trends
	 *            俱乐部（2种）：record，humor_trends
	 */
	public void collect(String cid, String nuid, String neirong_id, String type) {// Constants.BadiUrl+
																					// "praise_operate?uid="+uid+"&nid="+nid+"&nuid="+nuid+"&type="+type
		/*
		 * 用户收藏的操作接口 提交方式GET
		 * 
		 * @param $uid;//收藏人的id @param $nuid;//被收藏内容所属的用户id
		 * 
		 * @param $nid;//被收藏的内容id @param
		 * $type;//被收藏的类型（photo_img，record，humor_trends）
		 */
		String uid = Utils.getUid(LogReadingActivity.this);
		Utils.showPrgress(LogReadingActivity.this);
		CommonUtils.CommomGetfunction(LogReadingActivity.this,
				Constants.BadiUrl + "collect_operate?uid=" + uid + "&cid="
						+ cid + "&nuid=" + nuid + "&nid=" + neirong_id
						+ "&type=" + type, mHandler, 5, 6, 7, 8);
	}
}
